/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lucene.simple.search;

import java.io.File;
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/**
 *
 * @author Content Pilot
 * // Execute search query
 */
public class SimpleSearcher {
    
    public static void main(String[] args) throws Exception{
    
            File indexDir = new File("c:/luence_index/");
            String query = "common";
            int hits = 100;
            
            SimpleSearcher searcher = new SimpleSearcher();
            searcher.searchIndex(indexDir, query, hits);
    }
    
    
    private void searchIndex( File indexDir, String queryStr, int maxHits) throws Exception{
        Directory directory = FSDirectory.open(indexDir);
        
        IndexSearcher searcher = new IndexSearcher(directory);
        QueryParser queryParser = new QueryParser(Version.LUCENE_34, "contents", new SimpleAnalyzer(Version.LUCENE_34));
        Query query = queryParser.parse(queryStr);
        
        TopDocs topDocs = searcher.search(query, maxHits);
        
        ScoreDoc[] hits = topDocs.scoreDocs;
        for ( int i=0; i<hits.length; i++ ) {
            int docId = hits[i].doc;
            Document d = searcher.doc(docId);
            System.out.println(d.get("filename"));
        }
        
        System.out.println("Found: " + hits.length );
    }
}
